package com.example.demo1;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.val;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RestController
@RequestMapping("/session")
public class SessionController {
    @RequestMapping("/getC")
    public String getCookie(HttpServletRequest request, HttpServletResponse response){
        //获取参数
        //String[] cookies=request.getCookies();
        Cookie[] cookies = request.getCookies();
        if(cookies!=null){
            Arrays.stream(cookies).forEach(ck-> System.out.println(ck.getName()+":"+ck.getValue()));
        }
        return "获取cookie";
    }

    @RequestMapping("/getC2")
    public String getCookie2(@CookieValue("bite") String bite){
        return "从cookie中获取值，bite"+bite;
    }

    @RequestMapping("/setSess")
    public String setSess(HttpServletRequest request){
        //从cookie中获取到sessionId,根据sessionId获取session对象，如果没有获取到会创建一个session对象
        HttpSession session = request.getSession();
        session.setAttribute("name","zs");
        return "设置session成功";
    }

    @RequestMapping("/getSess")
    public String getSess(HttpServletRequest request){
        //从cookie中获取到sessionId,根据sessionId获取session对象
        HttpSession session = request.getSession();
        String name =(String) session.getAttribute("name");
        return "从session中获取name:"+name;
    }

    @RequestMapping("/getSess2")
    public String getSess(HttpSession session){
        String name =(String) session.getAttribute("name");
        return "从session中获取name:"+name;
    }

    @RequestMapping("/getSess3")
    public String getSess3(@SessionAttribute("name") String name){
        return "从session中获取name:"+name;
    }


    //User-Agent其实就是你的浏览器信息
    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request){
        String userAgent= request.getHeader("user-Agent");
        return "从Header中获取信息，userAget:"+userAgent;
    }

    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("user-Agent") String userAgent){
        return "从Header中获取信息，userAget:"+userAgent;
    }

}
